﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class hiddenPlatButton : MonoBehaviour {
	
	//public platformScript partner;
	Renderer rendererObject;
	public Texture2D offTex;
	public Texture2D onTex;
	Transform colidedPlayer;
	public List<hiddenPlatformScript> platforms;
	bool activated;
	
	// Use this for initialization
	void Start () {
		rendererObject = transform.GetChild(0).renderer;
	}
	
	// Update is called once per frame
	void Update () {
		if(!networkView.isMine)
			return;
		if(colidedPlayer)
		{
			if(colidedPlayer.position.y < transform.position.y)
				activate(false);
		}
	}
	
	void OnTriggerStay(Collider myCol)
	{
		if(activated || !networkView.isMine)
			return;
		
		if(myCol.tag == "Player")
		{
			if(myCol.transform.position.y > transform.position.y)
			{
				activate(true);
				colidedPlayer = myCol.transform;
			}
		}
		else if(myCol.tag == "Item")
		{
			activate(true);
		}
	}
	
	void OnTriggerExit(Collider myCol)
	{
		if(!networkView.isMine)
			return;
		//if(partner.isMoving)
		if(activated)
			activate(false);
			//networkView.RPC("activate",RPCMode.All,false);
	}
	
	
	void activate(bool isActive)
	{
		//partner.isMoving = isActive;
		activated = isActive;
		networkView.RPC("activateCollider",RPCMode.All,isActive);
		if(isActive)
		{
			if(rendererObject.material.mainTexture != onTex)
			{
				rendererObject.material.mainTexture = onTex;
			}
			
			foreach(hiddenPlatformScript go in platforms)
			{
				go.FadeIn();
				//go.collider.enabled = true;
			}
		}
		else
		{
			if(rendererObject.material.mainTexture != offTex)
			{
				rendererObject.material.mainTexture = offTex;
			}
			
			foreach(hiddenPlatformScript go in platforms)
			{
				go.FadeOut();
				//go.collider.enabled = false;
			}
			colidedPlayer = null;
		}
	}
	
	[RPC]
	void activateCollider(bool isActive)
	{
		if(isActive)
		{
			foreach(hiddenPlatformScript go in platforms)
			{
				go.collider.enabled = true;
			}
		}
		else
		{
			foreach(hiddenPlatformScript go in platforms)
			{
				go.collider.enabled = false;
			}
		}
			
			
	}
}
